<template>
  <label>文件数量
    <input type="number" v-model="tempFileSize">
  </label>
  <p v-show="isUse">当前文件选项已经应用</p>
  <p v-show="!isUse">当前文件选项未使用</p>
  <p>请注意:刷新操作将会覆盖掉所有未保存的信息,文件信息与其他信息之间是独立的</p>
  <button @click="refresh" type="button">刷新</button>
  <div>
    <div v-if="F5">
      <choose-file
          :r-id="id"
          :size="String(actualFileSize)"
          :form-data-msg="formDataMsg"
          :UPURl='globalConst.baseUrl+"user/resources/addFile/rar"'
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import {nextTick, ref, watch} from "vue";
import {globalConst} from "@constants/globalConst.js";
import {useGlobalConfirm} from "@utils/ConfirmDialogPlugin.js";
import ChooseFile from "@utils/choose-file.vue";

const props = defineProps<{
  rId: number,
}>()

let F5 = ref(true)
const tempFileSize = ref(4) // 临时值，用于输入
const actualFileSize = ref(4) // 实际传递给子组件的值
const formDataMsg = ref(new Map())
let id: number | string
id = Number(props.rId || -1)
if (id === -1) {
  throw Error('不存在的ID!')
}
const isUse = ref(true)

formDataMsg.value.set('atResource', id)
formDataMsg.value.set('updateFirstImg', actualFileSize.value.toString())

async function refresh() {
  const r = useGlobalConfirm()
  const b = await r("您确定要刷新吗?此操作将会丢失当前所有已选择的文件", {
    title: '是否刷新',
  })
  if (!b) return

  // 应用临时值到实际值
  actualFileSize.value = tempFileSize.value
  formDataMsg.value.set('updateFirstImg', actualFileSize.value.toString())

  F5.value = false
  await nextTick()
  F5.value = true
  isUse.value = true
}

// 监听临时值的变化，只更新状态提示
watch(tempFileSize, (newSize) => {
  if (newSize <= 1 || newSize > 100) {
    alert('错误的文件数量设置!当前允许的文件数量范围为1-100个')
    tempFileSize.value = actualFileSize.value // 重置为上一次的有效值
    return
  }
  isUse.value = false // 只是标记状态，不会触发子组件更新
})
</script>
